<?php

namespace App\Http\Controllers;

use App\Models\Menu;
use App\Models\Role;
use Illuminate\Http\Request;

class RoleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $validatedData  = $request->validate([
            'page' => 'nullable|integer',
            'pageSize' => 'nullable|integer',
        ]);
        $pageSize = $validatedData['pageSize'] ?? 20; // 默认每页20条记录
        $roles = Role::paginate($pageSize);
        // 构建响应数据
        $response = [
            'total' => $roles->total(),
            'page' => $roles->currentPage(),
            'pageSize' => intval($roles->perPage()),
            'rows' => $roles->items(),
        ];
        $responseJson = [
            'code' => 200,
            'message' => '',
            'data' => $response
        ];
        return response()->json($responseJson);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'id' => 'nullable|integer',
            'label' => 'required|string',
            'alias' => 'required|string',
            'sort' => 'required|integer',
            'status' => 'nullable|boolean',
            'remark' => 'nullable|string',
        ]);
        $validatedData['name'] = $validatedData['alias'];//为了兼容spatie，可以使用$user->hasRole('Super-Admin'))
        $validatedData['remark'] = $validatedData['remark'] ?? "";
        try {
            if (empty($validatedData['id'])) { // 新增逻辑
                $role = Role::create($validatedData);
                $responseJson = [
                    'code' => 200,
                    'message' => '新增成功',
                    'data' => $role
                ];
            } else { //更新逻辑
                $role = Role::findOrFail($validatedData['id']);
                $role->update($validatedData);
                $responseJson = [
                    'code' => 200,
                    'message' => '新增成功',
                    'data' => $role
                ];
            }
            return response()->json($responseJson);
        } catch (\Exception $e) {
            $responseJson = [
                'code' => $e->getCode(),
                'message' =>  '权限别名不能用重复',
                'data' => null,
            ];
            return response()->json($responseJson);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {

    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($ids)
    {
        if (strpos($ids, ',') !== false) {
            $numbers = explode(',', $ids);
            foreach ($numbers as $num) {
                $role = Role::findOrFail($num);
                $role->delete();
            }
        } else {
            $role = Role::findOrFail($ids);
            $role->delete();
        }
        $responseJson = [
            'code' => 200,
            'message' => '成功删除',
        ];
        return response()->json($responseJson);
    }

    /**
     * @param Request $request
     * @return void
     */
    public function setMenus(Request $request)
    {
        $req = $request->validate([
            'menus' => 'array',
            'role_id' => 'required'
        ]);
        if ($request->has('menus')) {
            $role = Role::find($req['role_id']);

            //        $role->givePermissionTo(19);
            //        $role->revokePermissionTo('edit articles');//角色删除权限
            $role->syncPermissions($req['menus']); // 同步权限
            $responseJson = [
                'code' => 200,
                'message' => '成功',
            ];
            return response()->json($responseJson);
        } else {
            $responseJson = [
                'code' => 400,
                'message' => '失败',
            ];
            return response()->json($responseJson);
        }
    }

    /**
     * @param Request $request
     * @return void
     */
    public function getMenus(Request $request)
    {
        $req = $request->validate([
            'role_id' => 'required'
        ]);
        $role = Role::find($request['role_id']);
        $permissions = $role->permissions->pluck('name');
        return response()->json($permissions);
    }
}
